//
//  AppDelegate.m
//  yunqiphone
//
//  Created by Maple on 13-7-10.
//  Copyright (c) 2013年 ci123.com. All rights reserved.
//
#import "AppDelegate.h"
//UMtrack
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
//控制器
#import "MLNavigationController.h"

#import "CirclesViewController.h"
#import "FindViewController.h"
#import "ActivityListViewController.h"
#import "UserCenterViewController.h"

#import "UIImage+extension.h"
#import "LaunchViewController.h"


//获取UDID
#import "OpenUDID.h"

#import "JPEngine.h"

#import <AdSupport/AdSupport.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
        
    application.applicationSupportsShakeToEdit= YES;
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    NSString *appStyleConfigString = [[NSBundle mainBundle] pathForResource:@"AppStyleConfigList" ofType:@"plist"];
    AppStyleConfig = [[NSArray alloc] initWithContentsOfFile:appStyleConfigString];
    appUserType = 1;
    
    Status_Gap = (Current_device_vesion >= 7.0) ? 20 : 0;
    NavHeight = Status_Gap + CUSTOM_NAV_HEIGHT;
    ContentStartPointY = (Current_device_vesion >= 7.0) ? 64 : 0;
    CGFloat inch = [UIUtils applicationSreenInch];
    if (inch == 5.5) {
        AppScreenInchType = AppScreenInch5_5;
    }else if (inch == 4.7) {
        AppScreenInchType = AppScreenInch4_7;
    }else if (inch == 4.0) {
        AppScreenInchType = AppScreenInch4_0;
    }else {
        AppScreenInchType = AppScreenInch3_5;
    }

            
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
   // [self _initTabBarView];
    //self.window.rootViewController = _tabBarController;
    LaunchViewController *launch = [[LaunchViewController alloc]init];
    self.window.rootViewController = launch;
    launch.endEvent = ^(NSDictionary *launchDic){
        [self _initTabBarView];
        self.window.rootViewController = _tabBarController;
    };

    
        
    //window初始化
    [self.window makeKeyAndVisible];
        
    
    return YES;
}

- (void)_initTabBarView
{
    NSMutableArray *tabItems = [[NSMutableArray alloc] init];
    _homeViewController = [[HomeViewController alloc] init];
    _homeViewController.title = @"社区";
    MLNavigationController *homeNav = [[MLNavigationController alloc] initWithRootViewController:_homeViewController];
    UITabBarItem *item1 = [[UITabBarItem alloc] initWithTitle:_homeViewController.title
                                                        image:[UIImage imageNamed:@""]
                                                          tag:1001];
    homeNav.tabBarItem = item1;
    [tabItems addObject:item1];
    
    CirclesViewController *circles = [[CirclesViewController alloc] init];
    circles.title = @"圈子";
    MLNavigationController *circleListNav = [[MLNavigationController alloc] initWithRootViewController:circles];
    UITabBarItem *item2 = [[UITabBarItem alloc] initWithTitle:circles.title
                                                        image:[UIImage imageNamed:@""]
                                                          tag:1002];
    circleListNav.tabBarItem = item2;
    [tabItems addObject:item2];
    
    FindViewController *findController = [[FindViewController alloc]init];
    findController.title = @"发现";
    MLNavigationController *categoryNav = [[MLNavigationController alloc] initWithRootViewController:findController];
    UITabBarItem *item3 = [[UITabBarItem alloc] initWithTitle:findController.title
                                                        image:[UIImage imageNamed:@""]
                                                          tag:1003];
    
    categoryNav.tabBarItem = item3;
    
    ActivityListViewController *activityView = [[ActivityListViewController alloc] init];
    activityView.title = @"活动";
    MLNavigationController *clubNav = [[MLNavigationController alloc] initWithRootViewController:activityView];
    UITabBarItem *item4 = [[UITabBarItem alloc] initWithTitle:activityView.title
                                                        image:[UIImage imageNamed:@""]
                                                          tag:1004];
    
    clubNav.tabBarItem = item4;
    
    UserCenterViewController *userCenterView = [[UserCenterViewController alloc] init];
    MLNavigationController *userNav = [[MLNavigationController alloc] initWithRootViewController:userCenterView];
    userCenterView.isTarView = YES;
    UITabBarItem *item5 = [[UITabBarItem alloc] initWithTitle:@"我"
                                                        image:[UIImage imageNamed:@""]
                                                          tag:1005];
    userNav.tabBarItem = item5;
    
    _tabViewControllers = [[NSMutableArray alloc] initWithObjects:homeNav,circleListNav,categoryNav,clubNav,userNav, nil];
    _tabBarController = [[BaseTabbarViewController alloc] init];
    _tabBarController.delegate = self;
    _tabBarController.viewControllers = _tabViewControllers;
    
    _rootViewControllers = @[_homeViewController,circles,findController,activityView,userCenterView];
    _rootViewController = _rootViewControllers[0];
    
    [[UITabBarItem appearance] setTitlePositionAdjustment:UIOffsetMake(0, -2)];
    [[UITabBarItem appearance] setTitleTextAttributes:@{UITextAttributeTextColor:[UIColor whiteColor]}
                                             forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:@{UITextAttributeTextColor:[UIColor whiteColor]}
                                             forState:UIControlStateSelected];
    
    [self changeTabbarStyleColor];
    if (Current_device_vesion >= 7.0) {
        NSInteger i = 1;
        for (UIViewController *controller in _tabBarController.viewControllers) {
            UITabBarItem *item = controller.tabBarItem;
            NSString *imageString = [NSString stringWithFormat:@"tabbar_icon_%ld", (long)i];
            NSString *seletedImageString = [NSString stringWithFormat:@"tabbar_icon_%ld", (long)i];
            if(appUserType==2){
                imageString = [NSString stringWithFormat:@"tabbar_icon_year_%ld", (long)i];
                seletedImageString = [NSString stringWithFormat:@"tabbar_icon_year_selected_%ld", (long)i];
            }
            
            item.image = [[UIImage imageNamed:imageString] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            item.selectedImage = [[UIImage imageNamed:seletedImageString] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            
            i++;
        }
    }else{
        [[UITabBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(1, CUSTOM_TABBAR_HEIGHT)]];
        [[UITabBar appearance] setSelectionIndicatorImage:[UIImage new]];
        NSInteger i = 1;
        for (UIViewController *controller in _tabBarController.viewControllers) {
            UITabBarItem *item = controller.tabBarItem;
            
            NSString *imageString = [NSString stringWithFormat:@"tabbar_icon_%ld", (long)i];
            NSString *seletedImageString = [NSString stringWithFormat:@"tabbar_icon_%ld", (long)i];
            if(appUserType==2){
                imageString = [NSString stringWithFormat:@"tabbar_icon_year_%ld", (long)i];
                seletedImageString = [NSString stringWithFormat:@"tabbar_icon_year_selected_%ld", (long)i];
            }
            
            [item setFinishedSelectedImage:[UIImage imageNamed:imageString]
               withFinishedUnselectedImage:[UIImage imageNamed:seletedImageString]];
            i++;
        }
    }
}

- (void)changeAppStyleColor {
    
    for (AllBaseViewController *controller in _rootViewControllers) {
        controller.navBackView.backgroundColor = [UIUtils getColorByString:AppStyleConfig[appUserType][@"navColor"]];
    }
}

- (void)changeTabbarStyleColor {
    
    UIColor *color = [UIUtils getColorByString:AppStyleConfig[appUserType][@"tabbarColor"]];
    UIColor *selectedColor = [UIUtils getColorByString:AppStyleConfig[appUserType][@"tabbarSelectedColor"]];
    [[UITabBar appearance] setShadowImage:[UIImage new]];
    [[UITabBar appearance] setBackgroundImage:[UIImage new]];
    [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageWithColor:selectedColor size:CGSizeMake((APP_SCREEN_WIDTH / 5), CUSTOM_TABBAR_HEIGHT)]];
    if (Current_device_vesion >= 7.0) {
        [[UITabBar appearance] setBarTintColor:color];
    }
}

- (void)checkNetwork {
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self ShowExclaHud:@"网络不给力，请检查网络！"];
        });
    };
    [reach startNotifier];
}

//实时监控网络状况
-(void)reachabilityChanged:(NSNotification*)note {
    Reachability * reach = [note object];
    
    appNetworkStatus = reach.currentReachabilityStatus;
    if(appNetworkStatus == NotReachable) {
        [self ShowExclaHud:@"网络不给力，请检查网络！"];
    }else {
        [_hud removeFromSuperview];
        _hud = nil;
    }
    [NOTIFICATION_CENTER postNotificationName:kNetworkStateChangedNotification
                                       object:self];
}


#pragma mark - MBProgressHUD

- (void)ShowExclaHud:(NSString *)title{
    if(_hud == nil) {
        _hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
    }
    [self showHudComplete:title success:NO];
}

- (void)showHudComplete:(NSString *)title success:(BOOL)success {
    NSString *name = success ? @"success" : @"excla";
    _hud.dimBackground = NO;
    _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
    _hud.mode = MBProgressHUDModeCustomView;
    if(title.length > 0) {
        _hud.labelText = title;
    }
    [_hud performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2];
}

//HOME退出
- (void)applicationWillResignActive:(UIApplication *)application
{
    //NSLog(@"WillResignActive");
    //程序暂行
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
}

//程序进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    
}


#pragma mark - UITabBarControllerDelegate

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSInteger tag = viewController.tabBarItem.tag - 1000;
    if (tag < 1) {
        return;
    }
    
    _rootViewController = _rootViewControllers[tag - 1];
    
}



@end
